//
//  WBHomeViewController.swift
//  WinsonWeibo
//
//  Created by Administrator on 2017/4/14.
//  Copyright © 2017年 Winson. All rights reserved.
//

import UIKit

// 定义全局常量， 尽量使用private 修饰，否则到处都可以访问
private let cellId = "cellId"

class WBHomeViewController: WBBaseViewController {

    /// 视图模型
    fileprivate lazy var listViewModel = WeiboStatusListViewModel()

    /// 重写父类的loadData方法
    override func loadData() {

        // 加载视图模型
        listViewModel.loadStatus(isPullUp: isPullUp) { (isSuccess, shouldRefresh) in

            // 恢复上拉刷新的标志
            self.isPullUp = false
            // 结束 刷新控件
            self.refreshControl?.endRefreshing()

            print("加载结束")
            if shouldRefresh {
                self.tableView?.reloadData()
            }
        }
    }

    /// 显示好友
    func showFriends() {
        let vc = WBTestViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - 重写父类的数据源方法， 但是并不调用super方法
extension WBHomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 1. 取出cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        // 2. 设置cell
        cell.textLabel?.text = listViewModel.statusList[indexPath.row].text
        // 3. 返回cell
        return cell
    }
}

// MARK: - 设置界面
extension WBHomeViewController {

    /// 重写父类方法
    override func setupTableView() {
        super.setupTableView()
        // 设置导航栏按钮
        // 无法高亮
        naviItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))

        // 注册cell 原型
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId)

        // 设置导航栏 标题按钮
        setupNavTitle()
    }

    fileprivate func setupNavTitle() {

        let title = WBNetworkManager.shared.userAccount.screen_name
        let button = WBTitleButton(title: title)
        naviItem.titleView = button
        button.addTarget(self, action: #selector(clickTitleButton(btn:)), for: UIControlEvents.touchUpInside)

    }

    @objc fileprivate func clickTitleButton(btn: UIButton) {

        btn.isSelected = !btn.isSelected;
    }
}
